package com.ilovepostcard;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.baidu.mapapi.a;
import com.ilovepostcard.controller.OffLineManager;
import com.ilovepostcard.utils.NetWorkUtil;
import com.ilovepostcard.utils.Utils;
import com.ilovepostcard.view.PostcardMainMenu;
import com.mobclick.android.MobclickAgent;

public class MainActivity extends MenuActivity {

	PostcardMainMenu mMenu;
	BroadcastReceiver receiver;
    @Override
    public void onCreate(Bundle savedInstanceState) {
       requestWindowFeature(Window.FEATURE_NO_TITLE);
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       Intent i = getIntent();
       boolean needResume = true;
       if(i != null)
       {
    	   String resume = i.getStringExtra("noresume");
    	   if(resume!= null && resume.equals("no"))
    		   needResume = false;
    		   
       }
        
        if (existPendingEdit() && needResume) {
            showContinueEditDialog();
        }
        
        if (!NetWorkUtil.isNetworkAvailable(this)) {
            Toast.makeText(this, "目前没有网络，只可以创建明信片哦", Toast.LENGTH_LONG).show();
        }
        else
        {
        	Utils.checkForUpdate(this,false);
        }
        
        mMenu = (PostcardMainMenu)findViewById(R.id.menus);
        mMenu.showButtonText(true);
        
        
        receiver = new BroadcastReceiver() {
            
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                int progress = intent.getIntExtra("progress", 0);
                notificationUpdate(action, progress);
            }
        };
        
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_DOWNLOADING);
        filter.addAction(ACTION_DOWNLOAD_SUCCESS);
        filter.addAction(ACTION_DOWNLOAD_FAIL);
        registerReceiver(receiver, filter);
    }
    
    public static final String ACTION_DOWNLOADING = "com.ilovepostcard.ACTION_DOWNLOADING";
    public static final String ACTION_DOWNLOAD_SUCCESS = "com.ilovepostcard.ACTION_DOWNLOAD_SUCCESS";
    public static final String ACTION_DOWNLOAD_FAIL = "com.ilovepostcard.ACTION_DOWNLOAD_FAIL";
    
    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }
    
    private void notificationUpdate(String action, int progress) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new Notification();
        notification.tickerText = "下载更新中";
        notification.icon = android.R.drawable.stat_sys_download;
        Intent intent = new Intent();
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification);
        
        
        if (ACTION_DOWNLOADING.equals(action)) {
            remoteViews.setTextViewText(R.id.notification_text, "下载更新中：" +progress+"%" );
            remoteViews.setProgressBar(android.R.id.progress, 100, progress, true);
            remoteViews.setViewVisibility(android.R.id.progress, View.VISIBLE);
            notification.flags |= Notification.FLAG_ONGOING_EVENT;
        } else if (ACTION_DOWNLOAD_SUCCESS.equals(action)) {
            remoteViews.setTextViewText(R.id.notification_text, "下载成功");
            remoteViews.setViewVisibility(android.R.id.progress, View.GONE);
//            notification.flags ^= Notification.FLAG_ONGOING_EVENT;
        } else if (ACTION_DOWNLOAD_FAIL.equals(action)) {
            remoteViews.setTextViewText(R.id.notification_text, "下载失败");
            remoteViews.setViewVisibility(android.R.id.progress, View.GONE);
//            notification.flags ^= Notification.FLAG_ONGOING_EVENT;
        }
        
        notification.contentView = remoteViews;
        notification.contentIntent = pendingIntent;
        notificationManager.notify(2012, notification);

    }
   
    @Override
    protected void onResume() {
    	MobclickAgent.onResume(this);
        super.onResume();
    }
    
    public void onPause()
    {
    	MobclickAgent.onPause(this);
    	super.onPause();
    }
    
    private boolean existPendingEdit() {
    	
		String name=OffLineManager.getInstance().getResumePC(this);
        return name != null;
    }
    
    private void showContinueEditDialog() {
        Utils.showConfirmDialog(MainActivity.this, "上次明信片没有创作完成，是否继续？", new Runnable() {
            public void run() {
            	Intent intent = new Intent(MainActivity.this, EditImageActivity.class);
            	String name=OffLineManager.getInstance().getResumePC(MainActivity.this);
                Bundle bundle =new Bundle();
                String from = "offline";
                bundle.putString("type",from);
                bundle.putString("name", name);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }, new Runnable() {
            public void run() {
            	OffLineManager.getInstance().clearResumeInfo(MainActivity.this);
            }
        });
    }

    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            doExist();
        }
        return super.onKeyDown(keyCode, event);
    }
}
